# -*- coding: utf-8 -*-
# @Time    : 2024/11/7 下午2:41
# @Author  : xiaowanzi
# @File    : public_tools.py

import re
import os
import time
import random
from selenium import webdriver

from base.grid_manager import delete_all_sessions
from base.log import logger
import threading
from base.project_path import get_project_path

Lock = threading.Lock()
Lock_delete_img = threading.Lock()
glob_project_run_id = ''


def set_glob_project_run_id(id_):
    global glob_project_run_id
    glob_project_run_id = id_


def get_project_run_id():
    return str(time.strftime("%Y%m%d%H%M%S")) + str(random.randint(0, 99)).zfill(2)


def get_run_id():
    return str(time.strftime("%Y%m%d%H%M%S")) + str(random.randint(0, 99)).zfill(2)


def get_case_id(self):
    return self.__dict__['_testMethodName']


def get_status():
    return "True"


def get_current_time():
    return time.strftime("%Y-%m-%d %H:%M:%S")


def release_driver(url):
    delete_all_sessions(url)


def delete_img(img_name):
    """
    删除不需要上传到数据库的错误截图
    :param img_name:错误截图的文件名
    :return:
    """

    with Lock_delete_img:
        path = get_project_path() + "\\img\\error_img"
        r = re.compile(r'{}.*'.format(img_name))  # 正则匹配错误截图文件
        for root, dirs, files in os.walk(path, topdown=False):
            for name in [x for x in files if r.findall(x)]:
                try:
                    os.remove(os.path.join(root, name))
                except Exception as e:
                    logger.info(f"删除文件失败{os.path.join(root, name)}\r\n报错信息:{e}")
                time.sleep(2)


def get_driver(selenium_ip=None, browser_type='chrome', proxy=None, mobile_chrome=False, incognito=False, remote=False):
    """
    获取driver
    :param selenium_ip:
    :param browser_type:
    :param proxy:
    :param mobile_chrome:
    :param incognito:
    :param remote:
    :return:
    """
    driver = None
    if selenium_ip is None:
        pass
        # selenium_ip = get_selenium_ip()
    if browser_type == "chrome":
        option = webdriver.ChromeOptions()
        # 关闭“chrome正受到自动测试软件的控制
        option.add_experimental_option('useAutomationExtension', False)
        option.add_experimental_option('excludeSwitches', ['enable-automation'])
        prefs = {"credentials_enable_service": False, "profile.password _manager_enabled": False}
        option.add_experimental_option("prefs", prefs)  # 不弹出保存密码框
        option.add_experimental_option("detach", True)  # 不自动关闭浏览器
        if proxy:
            option.add_argument("--proxy-server=%s" % proxy)  # 通过代理访间
        if mobile_chrome:
            # 设置手机型号，这设置为iPhone X
            option.add_argument("--auto-open-devtools-for-tabs")
            mobile_emulation = {"deviceName": "iPhone X"}
            option.add_experimental_option("mobileEmulation", mobile_emulation)
            # option.add_argument("user-agent=Android")  # 设置用户代理为Android
            # option.add_argument("--enable-features=MobileEmulatedDeviceMetricsOverride")
            # option.add_argument("--disable-gpu")  # 禁用GPU模拟
            # option.add_argument("--disable-infobars")
            # option.add_argument("--start-maximized")
            # option.add_argument("--no-first-run")
            # option.add_argument("--disable-setuid-sandbox")
            # option.add_argument("--no-sandbox")
            # option.add_argument("--test-type")
            # option.add_argument("--disable-extensions")
            # option.add_argument("--metrics-recording-only")
            # option.add_argument("--mute-audio")
        if incognito:
            option.add_argument("--incognito")  # 无痕模式

    if remote:
        driver = webdriver.Remote(command_executor='http://' + selenium_ip + ':4444', options=option,
                                  keep_alive=True)
    else:
        driver = webdriver.Chrome(options=option)

    return driver, selenium_ip
